package com.teamfractal.fracdustry.common.tools;

import com.teamfractal.fracdustry.common.util.energystorage.FDEnergyStorage;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.energy.CapabilityEnergy;

import java.util.concurrent.atomic.AtomicInteger;

public class ItemCharge {
    public ItemCharge(FDEnergyStorage energystorage, ItemStack stack, BlockEntity tile,int maxreceive){
        if(stack.getCapability(CapabilityEnergy.ENERGY).isPresent())
        {
            AtomicInteger capacity = new AtomicInteger(energystorage.getEnergyStored());
            boolean doContinue = stack.getCapability(CapabilityEnergy.ENERGY).map(handler ->
                    {if (handler.canReceive()) {
                        int received = handler.receiveEnergy(Math.min(capacity.get(), maxreceive), false);
                        capacity.addAndGet(-received);
                        energystorage.consumeEnergy(received);
                        tile.setChanged();
                        return capacity.get() > 0;
                    } else {
                        return true;
                    }
                    }
            ).orElse(true);
            if (!doContinue) {
                return;
            }
        }
    }
}
